package com.jicheng.controller;

import com.jicheng.Utils.Base64Utils;
import com.jicheng.Utils.DESEncryptUtil;
import com.jicheng.Utils.ResultMess;
import com.jicheng.dto.file.UploadDto;
import com.jicheng.ext.enums.ApiResponseCode;
import com.jicheng.ext.exceptions.BaseException;
import com.jicheng.ext.util.Validator;
import com.jicheng.service.IFileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.core.Context;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.UUID;

@Api(tags = "app-file(app文件)")
@RestController
@RequestMapping(value = "app-file", produces = "application/json;charset=UTF-8")
public class FileController {

    @Autowired
    private IFileService fileService;

    @ApiOperation(value = "上传app")
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public ResultMess upload(@RequestParam("file") MultipartFile file, String version,String comment) {
        return fileService.uploadApp(file,version,comment);
    }

    @ApiOperation(value = "下载app")
    @RequestMapping(value = "/download", method = RequestMethod.GET)
    public void downloadApp(@RequestParam("path")@ApiParam("path") String path, @Context HttpServletResponse response) {
        Validator.notNull("path",path);
        String[] split = path.split("/");
        int length = split.length;
        if (length < 1) {
            return;
        }
        String fileName = split[split.length-1];

        response.reset();
        response.setHeader("content-type", "application/octet-stream");
        response.setContentType("application/octet-stream");
        // 下载文件能正常显示中文
        ServletOutputStream outputStream ;
        try {
            response.setHeader("Content-Disposition", "attachment;filename=" +URLEncoder.encode(fileName,"UTF-8"));
            outputStream = response.getOutputStream();
        } catch (IOException e) {
            throw new BaseException(ApiResponseCode.服务器异常, "请重试");
        }
        fileService.downloadApp(path,outputStream);
    }

    /**
     * IO流读取图片
     * @return
     */
    @ApiOperation(value = "IO流读取图片")
    @RequestMapping(value = "/IoReadImage", method = RequestMethod.GET)
    public String IoReadImage(InputStream ips, HttpServletRequest request, HttpServletResponse response) throws IOException {
        ServletOutputStream out = null;
//        FileInputStream ips = (FileInputStream) decrypt;
        try {
//            ips = new FileInputStream(new File(imgPath));
            response.setContentType("multipart/form-data");
            out = response.getOutputStream();
            //读取文件流
            int len = 0;
            byte[] buffer = new byte[1024 * 10];
            while ((len = ips.read(buffer)) != -1){
                out.write(buffer,0,len);
            }
            out.flush();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            out.close();
            ips.close();
        }
        return null;
    }

    @ResponseBody
    @RequestMapping(value = "/getByte", method = RequestMethod.GET)
    public byte[] getByte(String path) {
        try {
            byte[] bytes = DESEncryptUtil.decryption2Byte("H:/key.k", path, "decrypt");
//            byte[] bytes = Base64Utils.fileToByte(path);
            return bytes;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    @ResponseBody
    @RequestMapping(value = "/getInputStream", method = RequestMethod.GET)
    public void getInputStream(String path, HttpServletResponse response) {
        try {
            byte[] bytes = DESEncryptUtil.decryption2Byte("H:/key.k", path, "decrypt");
//            byte[] bytes = Base64Utils.fileToByte(path);
            int lastIndexOf = path.lastIndexOf(".");
            String suffix = path.substring(lastIndexOf);
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=" +URLEncoder.encode(UUID.randomUUID()+suffix,"UTF-8"));

            response.getOutputStream().write(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}